package com.dfsoft.controller;

import com.dfsoft.libreoffice.OfficeConvertToPdfService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Objects;

/**
 * @author yuandf
 */
@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private OfficeConvertToPdfService officeConvertToPdfService;

    @PostMapping("/upload")
    public void upload(MultipartFile file, HttpServletResponse response) throws Exception {
        log.info(">>> file.getName()：【{}】，file.getOriginalFilename()：【{}】，file.getSize()：【{}】", file.getName(), file.getOriginalFilename(), file.getSize());
        final String fileSuffix = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");

        try (final ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            try {
                // 文件扩展名匹配了转换服务内的扩展名，则调用转换服务进行转换pdf
                // 如果DocumentFormatEnum.valueOf()找不到时抛出异常：IllegalArgumentException
                final OfficeConvertToPdfService.DocumentFormatEnum documentFormatEnum = OfficeConvertToPdfService.DocumentFormatEnum.valueOf(fileSuffix.toUpperCase());
                if (!Objects.isNull(documentFormatEnum)) {
                    officeConvertToPdfService.convert(file.getInputStream(), bos, fileSuffix);
                }
            } catch (IllegalArgumentException e) {
                bos.reset();
                try (InputStream inputStream = file.getInputStream()) {
                    //byte[] buffer = new byte[1024];
                    //int length;
                    //while ((length = inputStream.getInputStream().read(buffer)) > 0) {
                    //    bos.write(buffer, 0, length);
                    //}
                    bos.write(file.getBytes(), 0, file.getBytes().length);
                }
            }
            bos.close();
            final byte[] bytes = bos.toByteArray();
            response.setCharacterEncoding("UTF-8");
            // response.setHeader("Content-Disposition", "attachment; filename=" + new String(file.getOriginalFilename().getBytes("UTF-8"), "ISO-8859-1")); //
            response.setHeader("Content-Length", String.valueOf(bytes.length));
            ServletOutputStream out = response.getOutputStream();
            out.write(bytes);
            out.flush();
        }
    }
}
